package com.yhp.service.impl;

import com.yhp.bean.Menu;
import com.yhp.bean.Role;
import com.yhp.dao.impl.MiddleDaoImpl;
import com.yhp.dao.impl.RoleDaoImpl;
import com.yhp.service.RoleServlet;

import java.util.ArrayList;
import java.util.List;

public class RoleServletImpl implements RoleServlet {
    RoleDaoImpl roleDaoimpl = new RoleDaoImpl();
    MiddleDaoImpl middleDao = new MiddleDaoImpl();
    @Override
    public List<Role> getRole(int pageIndex,int pageSize) {
        return roleDaoimpl.getRole(pageIndex,pageSize);
    }

    @Override
    public List<Role> getRoleGo() {
        return roleDaoimpl.getRoleGo();
    }

    @Override
    public int ord(int id, int state) {
        return roleDaoimpl.ord(id,state);
    }

    @Override
    public int total() {
        return roleDaoimpl.total();
    }

    @Override
    public int addRole(Role role, String[] menuids) {
        int i1 = 0;
        try {
            int i = roleDaoimpl.addRole(role);
            i1 = middleDao.addMiddle(i, menuids);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return i1;
    }

    @Override
    public int deleteRole(int id) {
        int a = 0;
        try {
            int i = roleDaoimpl.deleteRole(id);
            int i1 = middleDao.deleteMiddleRole(id);
            a=1;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return a;
    }

    @Override
    public Role findById(int id) {
        Role role = null;
        try {
            role = roleDaoimpl.findById(id);
            List<Menu> byId1 = middleDao.findById(id);
            List<Menu> success = new ArrayList<>();//整理完毕的集合  分级的集合
            for (Menu menu : byId1) {
                if(menu.getUpMenuId()==0){
                    List<Menu> list =new ArrayList<>();

                    for (Menu menu1 : byId1) {
                        if(menu1.getUpMenuId()==menu.getMenuId()){
                            list.add(menu1);
                        }
                    }
                    menu.setSuccessList(list);

                    success.add(menu);
                }
            }
            role.setMenuList(success);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return role;
    }

    @Override
    public int updateRole(Role role,String[] menuIds) {
        int a = 0;
        try {
            a = 0;
            int i = roleDaoimpl.updateRole(role);
            int i1 = middleDao.updateMiddleRole(role, menuIds);
            a=1;
        } catch (Exception e) {
            e.printStackTrace();
        }


        return a;
    }
}
